<?php
declare(strict_types=1);

namespace app\admin\controller\system;

use app\admin\model\AuthRule as AuthRuleModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use app\common\Attribute\ClassTitle;
use app\common\Attribute\RequestMethod;
use app\common\Attribute\RequestTitle;
use app\common\controller\AmisAdminController;
use app\common\support\Tree;
use hg\apidoc\annotation as Apidoc;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Request;
use LhpAmis\Renderers\Amis;
/**
 * 权限管理
 **/
#[ClassTitle('权限')]
class AuthRule extends AmisAdminController
{
    /**
     * 列表
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('列表')]
    public function index(Request $request): \think\response\Json
    {
        if ($request->isPost()) {
            // $order = $request->param('order', 'ASC');
            $wheres = [];
            // $list_rows = $this->request->param('list_rows');
            // dump( $list_rows);die;
            $data = AuthRuleModel::where($wheres)
                // ->order('create_time', $order)
                ->select()
                ->toArray();
            $Tree = new Tree();
            $data = $Tree->withConfig('buildChildKey', 'children')
                ->withData($data)
                ->build();

            return $this->data($data);
        }
        $amis = Amis::make()->TableBuilder()
            ->setTitle('列表')
            ->setSearchItems([
                ['parent_id', '上级权限'],
                ['title', '权限名称'],
                ['url', '请求地址'],
                ['description', '描述'],
                ['listorder', '排序值', 'number'],
                ['is_need_auth', '验证权限', 'switch'],
                ['is_system', '系统权限', 'switch'],
                ['create_time', '创建时间', 'date'],
            ])
            ->addColumns([
                ['id', 'ID'],
                ['parent_id', '上级权限'],
                ['app_name', '所属应用'],
                ['title', '权限名称'],
                ['url', '请求地址'],
                ['method', '请求方法'],
                ['description', '描述'],
                ['listorder', '排序值', 'number'],
                ['is_need_auth', '验证权限', 'switch'],
                ['is_system', '系统权限', 'switch'],
                ['right_button', '操作', 'btn'],
            ])
            ->addTopButtons('create,delete')
            ->addRightButtons('edit,delete')
        ;
        return $this->data($amis);
    }

    /**
     * 创建
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('创建')]
    public function create(Request $request): \think\response\Json
    {
        if ($request->isPost()) {

            $data = $request->all();
            try {
                $this->validate($data, [
                    'parent_id' => 'require',
                    'title' => 'require',
                    'url' => 'require',
                ], [
                    'parent_id.require' => '父id必须',
                    'title.require' => '名称必须',
                    'url.require' => 'url必须',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = AuthRuleModel::make()->create([
                'parent_id' => $data['parent_id'],
                'title' => $data['title'],
                'url' => $data['url'],
                'description' => $data['description'] ?? '',
                'listorder' => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system' => $data['is_system'] ?? 0,
            ]);
            if ($result->isEmpty()) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }

        $amis = Amis::make()->FormBuilder()
            ->addFormItems([
                ['parent_id', '上级权限', 'select', '', '', (string) url('getTreeList'), ["searchable" => true, "selectMode" => "tree",]],
                ['url', '请求地址'],
                ['description', '描述'],
                ['listorder', '排序值', 'number'],
                ['is_need_auth', '验证权限', 'switch'],
                ['is_system', '系统权限', 'switch'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }


    /**
     * 更新
     * @param string $id
     * @param \think\Request $request
     * @return \think\response\Json
     */
    #[RequestMethod(['GET,POST'])]
    #[RequestTitle('更新')]
    public function update(string $id, Request $request): \think\response\Json
    {
        try {
            $authRule = AuthRuleModel::where('id', $id)->findOrEmpty();
            if ($authRule->isEmpty()) {
                return $this->error('权限不存在');
            }
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error('权限不存在');
        }
        if ($this->request->isPost()) {
            $data = $request->all();

            try {
                $this->validate($data, [
                    'parent_id' => 'require',
                    'title' => 'require',
                    'url' => 'require',
                ], [
                    'parent_id.require' => '父id必须',
                    'title.require' => '名称必须',
                    'url.require' => 'url必须',
                ]);
            } catch (ValidateException $e) {
                return $this->error($e->getError());
            }
            $result = $authRule->save([
                'parent_id' => $data['parent_id'],
                'title' => $data['title'],
                'url' => $data['url'],
                'description' => $data['description'] ?? '',
                'listorder' => $data['listorder'] ?? 100,
                'is_need_auth' => $data['is_need_auth'] ?? 0,
                'is_system' => $data['is_system'] ?? 0,
            ]);
            if (!$result) {
                return $this->error('错误');
            }

            return $this->success('成功');
        }


        $amis = Amis::make()->FormBuilder()
            ->setApi(BaseApiPost())
            ->data($authRule->toArray())
            ->addFormItems([
                ['id', 'ID', 'hidden'],
                ['parent_id', '上级权限', 'select', '', '', (string) url('getTreeList'), ["searchable" => true, "selectMode" => "tree",]],
                ['url', '请求地址'],
                ['description', '描述'],
                ['listorder', '排序值', 'number'],
                ['is_need_auth', '验证权限', 'switch'],
                ['is_system', '系统权限', 'switch'],
            ])
            ->setSubmitAction();
        return $this->data($amis);
    }

    /**
     * 删除
     * @param string $id
     * @return \think\response\Json
     */
    #[RequestMethod(['DELETE'])]
    #[RequestTitle('删除')]
    public function delete(string $id): \think\response\Json
    {
        try {
            $row = AuthRuleModel::where('id', $id)->find();
            if (!$row) {
                return $this->error('错误');
            }
            $row->delete();

            return $this->success('成功');
        } catch (\Throwable $th) {
            return $this->error('错误:' . $th->getMessage());
        }
    }

    /**
     * 获取树结构选项
     * @return \think\response\Json
     */
    #[RequestMethod(['GET'])]
    #[RequestTitle('获取树结构选项')]
    public function getTreeList()
    {
        return $this->data(AuthRuleModel::getTreeList());
    }
}
